#pragma once
#ifndef WEBSOCKETCLIENT_H
#define WEBSOCKETCLIENT_H
#include "mongoose.h"
#include <string>
#include <functional>

class WebSocketClient {
public:
    WebSocketClient(const std::string& url);
    ~WebSocketClient();

    void connect();
    bool WaitForConnection(size_t time);
    void disconnect();
    void sendMessage(const std::string& message);
    void SendBinary(const void* buf, size_t len);
    bool isConnected() const;
    void pool(int ms = 0);

    void setOnMessage(std::function<void(WebSocketClient* pClient, const char* buf, size_t len)> callback);
    void setOnOpen(std::function<void()> callback);
    void setOnClose(std::function<void()> callback);
    void setOnError(std::function<void(const std::string&)> callback);

private:
    static void eventHandler(struct mg_connection* c, int ev, void* ev_data);

    struct mg_mgr mgr;
    struct mg_connection* conn;
    std::string url;
    bool connected;

    std::function<void(WebSocketClient* pClient, const char* buf ,size_t len)> onMessage;
    std::function<void()> onOpen{};
    std::function<void()> onClose{};
    std::function<void(const std::string&)> onError;
};

#endif // WEBSOCKETCLIENT_H